package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ZW
 * @DATE 2020/7/23 15:04
 * @Description  spu监听类
 **/
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ListenPoint(schema = "changgou_goods", table = "tb_spu")
    public void goodsUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //获取改变之前的数据并封装到map集合
        Map<String, String> beforeMap = new HashMap<>();
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        for (CanalEntry.Column column : beforeColumnsList) {
            beforeMap.put(column.getName(), column.getValue());
        }

        //获取改变之后的数据并封装到map集合
        Map<String, String> afterMap = new HashMap<>();
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        for (CanalEntry.Column column : afterColumnsList) {
            afterMap.put(column.getName(), column.getValue());
        }

        //判断商品是否上架
        if (beforeMap.get("is_marketable").equals("0") && afterMap.get("is_marketable").equals("1")) {
            //即该商品是最新上架的商品,将商品的spuId发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", afterMap.get("id"));
        }

        //判断商品是否下架
        if (beforeMap.get("is_marketable").equals("1") && afterMap.get("is_marketable").equals("0")) {
            //即该商品是最新上架的商品,将商品的spuId发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE, "", afterMap.get("id"));
        }

        //获得最新审核通过的商品
        if (beforeMap.get("status").equals("0") && afterMap.get("status").equals("1")){
            //将商品的spuId发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.PAGE_CREATE_QUEUE, "", afterMap.get("id"));
        }

    }
}